const app = getApp();
Component({
  name:"customPage",
  properties: {
    receiveData: {
      type: String,
      value: 'default value',
    },
    showFooter: {
      type: String,
      value: '',
    },
  },
  data: {
    // 这里是一些组件内部数据
    showPopup:false,
    renderData: null,
    PaiXuPartials:null, 
    kefuCount: 0,
    footerCount: 0,
    authorizationCount:0,
    defaultTop:0,
    footerImgState: false,
    sendOptionData: null,
    showAddressForm: false,
    userInfoFormCommitId: '',
    showUserForm: false,
    showFooterState:true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    showBannerState:true,
    paramData:null,
  },
  ready: function () {
      this.initFun();
  },
  methods: {
    initFun:function(params){
        let that = this;
        app.globalData.footerCount++;
        app.globalData.authorizationCount++;
        let paramData=params?params:that.data.receiveData;
        that.setData({paramData:paramData})
        console.log("===that.data.receiveData====", that.data.receiveData,paramData)
        if (that.data.showFooter){
          that.setData({ showFooterState:false})
        }
        let jsonData='';
        try {
          jsonData = JSON.parse(paramData);
        } catch (e) {
          jsonData = paramData
        }
        that.setData({ authorizationCount: app.globalData.authorizationCount, footerCount: app.globalData.footerCount, showPopup: jsonData.state||false})
        console.log('zujian', paramData, that.data.showPopup, that.data.authorizationCount,app.globalData.loginUser)
        let userInfo=app.globalData.loginUser?{
            telno: app.globalData.loginUser?app.globalData.loginUser.telno:'',
            headimg: app.globalData.loginUser.userIcon||'',
            nickname: app.globalData.loginUser.nickname||'',
            userTip: app.globalData.loginUser.userTip||'',
            sex: app.globalData.loginUser.sex,
          }:{}
        that.setData({
          loginUser: app.globalData.loginUser,
          setting: app.globalData.setting,
          userInfo:userInfo,
        })
        console.log('setting', that.data.setting)
        console.log('app.globalData.loginUser', that.data.loginUser)
    // 获取用户信息
        if (that.data.canIUse) {
          console.log('==that.data.canIUse===', that.data.canIUse);
          app.globalData.userInfoReadyCallback = res => {
            console.log("=====userInfo====",res)
            that.setData({
              userInfo: res.userInfo,
            })
          }
        }
        that.getParac();
    },
    setShowBannerStateFun:function(state){
        let that=this;
        // that.setData({showBannerState:state})
        that.selectComponent("#indexBanner").stopBannerFun(state);
    },
    // setShowBannerStateFun:function(state){
    //     let that=this;
    //     that.setData({showBannerState:state})
    // },
    setPopupState:function(state){
        let that=this;
        that.setData({ showPopup:state })
    },
    toChangeUserInfo: function (userInfo) {
      let that = this;
      var customIndex = app.globalData.AddClientUrl("/change_user_info.html", userInfo, 'post')
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: app.globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res.data)
          if (res.data.errcode == '0') {
            wx.showToast({
              title: '修改成功',
              icon: 'success',
              duration: 2000
            })
          }
          that.setData({ showUserForm: false })
          that.loginIn()
        },
        fail: function (res) {
          app.globalData.loadFail()
        },
        complete: function () {
          that.setData({ butn_show_loading: false })
        }
      })
    },

    loginIn: function (data) {
      app.globalData.get_session_userinfo()
      return
      console.log(data)
      var that = this;
      var loginUrl = app.globalData.AddClientUrl("Client.User.Login", data, 'post')
      wx.request({
        url: loginUrl.url,
        data: loginUrl.params,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          console.log(res.header)
          var header = res.header
          var cookie = null
          if (!!header['Set-Cookie']) {
            cookie = header['Set-Cookie']
          }
          if (!!header['set-cookie']) {
            cookie = header['set-cookie']
          }
          console.log(cookie)
          if (res.data.errcode == 0) {
            wx.setStorage({
              key: "cookie",
              data: cookie
            })
            app.globalData.header = {
              'content-type': 'application/json', // 默认值
              'Cookie': cookie
            }
            app.globalData.cookie = cookie
            app.globalData.loginUser = res.data.relateObj
            that.setData({ loginUser: res.data.relateObj })
            wx.setStorage({
              key: "loginUser",
              data: res.data.relateObj
            })
            wx.navigateBack()
          }
          else {
            wx.showToast({
              title: '失败',
              icon: 'loading',
              duration: 1500
            })
          }
        },
        fail: function (res) {
          console.log("fail")
          app.globalData.loadFail()
        }
      })
    },
    getDataFun: function (e) {
      let that = this;
      console.log("===getDataFun===", e, e.detail.formId)
      if (e.detail.formId) {
        let userInfo = that.data.userInfo;
        userInfo.userInfoFormCommitId = e.detail.formId
        that.toChangeUserInfo(userInfo)
      };
    },
    submitData: function (e) {
      let that = this;
      console.log("===getDataFun===", e, e.detail.formId)
      that.selectComponent("#userForm").formSubmit();
    },
    resEventFun: function (event){
      let that=this;
      console.log("==========resEventFun=========", event)
      let resEventData = event.detail.resEventData;
      that.triggerEvent('resEvent', { resEventData }, {})
    },
    
    bindGetUserInfo: function (e) {
      let that = this;
      that.setData({ showPopup: false })
      console.log(that.data.showPopup)
      console.log(e.detail.userInfo)
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        console.log('用户按了允许授权按钮')
        if (app.globalData.loginUser && app.globalData.loginUser.platformUser&&(!app.globalData.loginUser.platformUser.nickname||!app.globalData.loginUser.platformUser.headimgurl)) {
           app.globalData.sentWxUserInfo(app.globalData.loginUser,function(loginUser){
               that.triggerEvent('refreshFun',loginUser) //myevent自定义名称事件，父组件中使用
           })
        }else{
            that.triggerEvent('refreshFun',app.globalData.loginUser) //myevent自定义名称事件，父组件中使用
        }
      } else {
        console.log('用户按了拒绝按钮')
        //用户按了拒绝按钮
      }
    },
    cancel: function () {
      this.setData({ showPopup: false })
    },
    getParacFun: function (res) {
      let that = this;
      let url
      let jsonData;
      let params = { version: app.globalData.version };
      try {
        jsonData = JSON.parse(that.data.paramData);
        url = jsonData.url
      } catch (e) {
        jsonData = that.data.paramData
        console.log(e); 
        url = jsonData
      }
      if (jsonData.params) {
        params = Object.assign({}, params, jsonData.params)
      }
      if (res){
        params = Object.assign({}, params, res)
      }
      console.log("params", params)
      var customIndex = app.globalData.AddClientUrl("/custom_page_" + url + ".html", params, 'get', '1')
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          console.log("====== res.data=========", res.data)
          let data = res.data;
          if (!data.errcode | data.errcode == '0') {
            if (data.channelName != "index") {
              if (jsonData.title && jsonData.title == "noTitle") {
                console.log("======不设置标题=======")
              } else (
                wx.setNavigationBarTitle({
                  title: data.channelTitle,
                })
              )
            }
            wx.hideLoading()
            app.globalData.renderData = data
            that.setData({ renderData: data })
            if (data.partials.length == 0) {
              that.setData({ PaiXuPartials: null })
            } else {
                let locationAreaData = wx.getStorageSync('selectAreaData_'+app.globalData.clientNo)||''
                if (locationAreaData){
                  console.log("拥有区域", locationAreaData)
                  let setAreaDataParams={areaId:locationAreaData.id||0};
                  that.setAreaDataFun(setAreaDataParams,function(){
                      that.getPartials();
                  });
                } else {
                    let num=0;
                    for(let i=0;i<data.partials.length;i++){
                        if(data.partials[i].partialType == 28&&data.partials[i].androidTemplate=='location_area'){
                            num++
                            that.getLoctionArea(res);
                            break;
                        }
                    }
                    if(num==0){
                        that.getPartials();
                    }
                }
            }
          } else {
            console.log('加载失败')
          }
        },
        fail: function (res) {
          console.log('------------2222222-----------',res)
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: '加载失败，点击【确定】重新加载',
            success: function (res) {
              if (res.confirm) {
                that.getParac()
              } else if (res.cancel) {
                app.globalData.toIndex()
              }
            }
          })
        }
      })
    },
    getParac: function () {
      let that = this;
      let params={}
      let locationAddressData = wx.getStorageSync('selectAddressData'+app.globalData.clientNo) || ''
      if (locationAddressData) {
        params = Object.assign({}, params, {
          "longitude": locationAddressData.longitude,
          "latitude": locationAddressData.latitude,
        })
        console.log("====params====已有经纬度", params,locationAddressData)
        that.getParacFun(params)
      } else {
        wx.getLocation({
          type: 'gcj02',
          success: function (res) {
            console.log("=====getLocationAddress1111111====", res)
            params.latitude = res.latitude
            params.longitude = res.longitude
            app.globalData.setStorageFun("localPoint",params);
            app.globalData.localPoint=params
            console.log("====params====获取当前地理位置", params)
            that.getParacFun(params)
          },
          fail: function (res) {
            console.log("fail",res)
            app.globalData.loadFail()
            that.getParacFun(params)
          }
        })
      }
    },
    getPartials: function () {
      let that=this;
      var partials = that.data.renderData.partials;
      console.log("=====partials=====", partials)
      var PaiXuPartials = [];
      //排序
      if (partials && partials.length) {
        for (let i = 0; i < partials.length; i++) {
          // 产品标签的转化为数组start
          if (partials[i].partialType == 6 && partials[i].androidTemplate=="footer-img"){
            console.log("====存在浮动图片====", that.data.footerImgState)
            that.setData({ footerImgState: true })
            console.log("====存在浮动图片====", that.data.footerImgState)
          }
          if (partials[i].partialType == 24 ){
            that.data.kefuCount++;
          }
          console.log('=========that.kefuCount=====', that.data.kefuCount)
          if (typeof (partials[i].jsonData) == "string") {
            partials[i].jsonData = JSON.parse(partials[i].jsonData)
          } else {
            continue;
          }

          console.log("=====partials=====", partials)
          PaiXuPartials.push(partials[i]);
        }
        wx.getSystemInfo({
          success: function (res) {
            let screenHeight = Math.floor(res.screenHeight * 0.618);
            let kefuHeight = Math.floor(that.data.kefuCount * ((65 + 20) / 2))
            console.log('===screenHeight====', screenHeight);
            let defaultTop = screenHeight - kefuHeight
            console.log('defaultTop', defaultTop)
            that.setData({
              defaultTop: defaultTop
            })
          },
        })
      }
      this.setData({ PaiXuPartials: PaiXuPartials })
      console.log(this.data.PaiXuPartials)
    },
    setAreaDataFun:function(params,callBackFun){
        let that=this;
        var customIndex = getApp().globalData.AddClientUrl("/setLocateArea.html", params, 'post');
        wx.request({
          url: customIndex.url,
          data:customIndex.params,
          header: getApp().globalData.headerPost,
          method: 'POST',
          success: function (res) {
            console.log("=====getAllAreaFun====", res.data);
            let data = res.data.relateObj;
            if(res.data.errcode==0){
              console.log("设置成功", that.selectAddressData);
              wx.setStorageSync('selectAreaData_'+getApp().globalData.clientNo, data);
            }else{
              wx.showToast({
                title: res.data.errMessage,
                image: '/wxcomponents/images/icons/tip.png',
                duration: 2000
              })
            }
            if(callBackFun){
                callBackFun()
            }else{
                let url='select_area.html';
                that.tolinkUrl(url);
                that.getPartials();
            }
            // that.getPartials();
            wx.hideLoading();
          },
          fail: function (res) {
            wx.hideLoading();
            getApp().globalData.loadFail();
            that.getPartials();
          }
        });
    },
    getLoctionArea:function(pageParam){
        let that = this
        let param = {}
        param['type'] = 1
        param.longitude = pageParam.longitude
        param.latitude = pageParam.latitude
        var customIndex = app.globalData.AddClientUrl("/wx_search_nearest_area.html", param, 'get')
        wx.request({
          url: customIndex.url,
          header: app.globalData.header,
          success: function (res) {
            console.log("=====getLoctionArea====", res.data)
            let data = res.data.relateObj
            let setAreaDataParams={areaId:data.id||0};
            that.setAreaDataFun(setAreaDataParams);
            wx.hideLoading()
          },
          fail: function (res) {
            wx.hideLoading()
            app.globalData.loadFail()
          }
        })
    },
    // 这里是一个自定义方法
    tolinkUrl: function (e) {
      console.log("e.currentTarget.dataset.link=====", e)
      let linkUrl = e.currentTarget?e.currentTarget.dataset.link:e
      app.globalData.linkEvent(linkUrl)
    },    onReachBottom:function(){        let that=this;        let listTypePageList=that.selectAllComponents(".listTypePage");        console.log("===onReachBottom===",listTypePageList);        if(listTypePageList&&listTypePageList.length!=0){            for(let i=0;i<listTypePageList.length;i++){                if(listTypePageList[i].data.receiveData&&listTypePageList[i].data.receiveData.jsonData&&listTypePageList[i].data.receiveData.jsonData.count==-1){                    if(listTypePageList[i].onReachBottom){                        listTypePageList[i].onReachBottom()                    }                }            }        }    },
  },
})